import traceback
from os import name
import threading
from socket import *
# import tqdm                                 # 进度条，可自行加上
 
   
 
lock = threading.Lock()                     # 确保 多个线程在共享资源的时候不会出现脏数据
openNum=0                                   # 端口开放数量统计
threads=[]                                  # 线程池
 
def portscanner(host,port):
    global openNum
    try:
        s=socket(AF_INET,SOCK_STREAM)
        # s.settimeout(1000)
        s.connect((host,port))
        openNum+=1
        print(f"{port} open")
        s.close()
    except Exception as e:
        # traceback.print_exc()
        pass
 
def main(ip,ports=range(1, 65535)):            # 设置 端口缺省值0-65535
    setdefaulttimeout(1)
    for port in ports:
        portscanner(ip, port)
    #     t=threading.Thread(target=portscanner,args=(ip,port))
    #     threads.append(t)
    #     t.start()
    # for t in threads:
    #     t.join()
    print(f"PortScan is Finish ，OpenNum is {openNum}")  
 
if __name__ == '__main__':
    ip="220.184.140.126"
    # main(ip,[80, 8888])          # 输入端口扫描
    main(ip)                               # 全端口扫描